package cn.itcast.usermanager.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mysql.jdbc.StringUtils;
import com.sun.tools.internal.ws.processor.model.Request;

import cn.itcast.usermanager.mapper.UserMapper;
import cn.itcast.usermanager.pojo.User;

@RequestMapping("rest/user")
@org.springframework.stereotype.Controller
public class RestfulController{
	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping("rest")
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView m = new ModelAndView();
		
		m.setViewName("hello");
		m.addObject("msg", "restful");
		
		return m;
	}
	
	@RequestMapping(value="{id}",method=RequestMethod.POST)
	public ResponseEntity<User> queryById(@PathVariable("id") Long id) {
		try {
			if (id.longValue() < 1) {
				//400
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			User user = this.userMapper.queryById(id);
			
			if (user == null) {
				//404
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}
			
			//201
			return ResponseEntity.status(HttpStatus.CREATED).body(null);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	
	
	}
	
	
	@RequestMapping(method=RequestMethod.POST)
	public ResponseEntity<Void> saveUser(User user) {
		try {
			if (user == null) {
				//400
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			
			this.userMapper.insertUser(user);
			

				//201
			return ResponseEntity.status(HttpStatus.CREATED).body(null);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	
	
	}

}
